<template>
  <div class="pending-operation-management-container base-page-container">
    <!-- 搜索区域 -->
    <common-search v-model="searchForm" :search-items="searchItemsConfig" @search="handleSearch" @reset="resetSearchForm">
      <!-- 时间范围插槽模板 -->
      <template #timeRange="{ form }">
        <el-radio-group v-model="form.timeRange">
          <el-radio label="近7天">近7天</el-radio>
          <el-radio label="近30天">近30天</el-radio>
          <el-radio label="近3个月">近3个月</el-radio>
        </el-radio-group>
      </template>
    </common-search>

    <!-- 操作按钮区域 -->
    <div class="operation-buttons-container">
      <action-buttons 
        :selected-data="selectedRows" 
        :buttons="buttonsConfig"
        @add="handleReceive"
        @export="handleExport"
      />
      <div class="extra-buttons">
        <el-button @click="handlePrintOrder">
          <el-icon><Printer /></el-icon>打印入库单
        </el-button>
        <el-button @click="handlePrintBarcode">
          <el-icon><Printer /></el-icon>打印商品条码
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <custom-table
      :data="tableData"
      :columns="tableColumns"
      :loading="tableLoading"
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      table-id="pending-operation-table"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <!-- 状态列的自定义插槽 -->
      <template #status="{ row }">
        <el-tag :type="getStatusTagType(row.status)">
          {{ row.status }}
        </el-tag>
      </template>
      
      <!-- 操作列 -->
      <template #operation="{ row }">
        <theme-button link @click="handleView(row)">查看</theme-button>
        <theme-button link @click="handleLogView(row)">日志</theme-button>
      </template>
    </custom-table>

    <!-- 提示弹窗 -->
    <el-dialog v-model="tipDialogVisible" title="提示" width="400px">
      <div class="warning-message">
        <el-icon color="#E6A23C"><WarningFilled /></el-icon>
        <span>只支持单货主多订单进行多单入库</span>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tipDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 收货入库弹窗 -->
    <el-dialog v-model="receiveDialogVisible" title="收货入库" width="1200px" destroy-on-close>
      <div class="receive-dialog-container">
        <!-- 收货信息头部 -->
        <div class="receive-header">
          <div class="header-item">
            <span class="label">外部单号：</span>
            <el-input v-model="receiveForm.externalOrderNo" clearable class="header-input" disabled></el-input>
          </div>
          <div class="header-item">
            <span class="label">入库订单号：</span>
            <el-input v-model="receiveForm.orderNo" clearable class="header-input" disabled></el-input>
          </div>
          <div class="header-item">
            <span class="label required">入库时间：</span>
            <el-date-picker
              v-model="receiveForm.inboundTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择日期时间"
              class="header-input"
            ></el-date-picker>
          </div>
          <div class="header-item">
            <span class="label">供应商名称：</span>
            <el-input v-model="receiveForm.supplierName" clearable class="header-input" disabled></el-input>
          </div>
        </div>

        <!-- 商品搜索和操作栏 -->
        <div class="product-search-action-container">
          <action-buttons
            :buttons="{import: { visible: false, order: 2, type: themeType.value || 'primary' }}"
            :custom-buttons="[{
              name: 'recommend-location',
              customLabel: '推荐货位',
              customIcon: 'Refrigerator',
              type: themeType.value || 'primary',
              iconColor: themeColor,
              order: 1,
              visible: true
            }]"
            @button-click="handleRecommendLocation"
          />	 
          <!-- 商品条码/编号搜索 -->
          <div class="product-search-area">
            <span class="search-title">商品条码/编号</span>
            <div class="search-input-with-action">
              <el-input 
                v-model="receiveForm.productSearch" 
                placeholder="扫描商品条码/输入商品编号" 
                class="product-search-input"
                @keyup.enter="handleAddProduct"
				clearable
              >
                <template #append>
                  <el-button @click="handleAddProduct">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>
          </div>

          <!-- 上架货位 -->
          <div class="location-select-area">
            <span class="search-title">上架货位</span>
            <el-select clearable v-model="receiveForm.storageLocation" class="location-select" placeholder="请选择上架货位">
              <el-option
                v-for="item in storageLocationOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </div>

        <!-- 商品表格 -->
        <div class="product-table-container">
          <el-table
            :data="receiveProducts"
            border
            style="width: 100%"
            v-loading="receiveProductsLoading"
            @selection-change="handleProductSelectionChange"
          >
            <el-table-column type="selection" width="55" fixed="left"></el-table-column>
            <el-table-column label="商品编码" prop="productCode" min-width="100"></el-table-column>
            <el-table-column label="商品名称" prop="productName" min-width="120"></el-table-column>
            <el-table-column label="规格" prop="spec" min-width="80"></el-table-column>
            <el-table-column label="单位" prop="unit" min-width="60"></el-table-column>
            <el-table-column label="长(cm)" min-width="80">
              <template #default="{ row }">
                <el-input v-model.number="row.length" type="number" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="宽(cm)" min-width="80">
              <template #default="{ row }">
                <el-input v-model.number="row.width" type="number" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="高(cm)" min-width="80">
              <template #default="{ row }">
                <el-input v-model.number="row.height" type="number" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="体积(m³)" min-width="120">
              <template #default="{ row }">
                <el-input v-model.number="row.volume" type="number" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="重量(kg)" min-width="120">
              <template #default="{ row }">
                <el-input v-model.number="row.weight" type="number" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="预收数量" prop="planQty" min-width="120"></el-table-column>
            <el-table-column label="入库数量" min-width="140">
              <template #default="{ row }">
                <div class="qty-editor">
                  <el-icon class="qty-icon" size="30" @click="decreaseQty(row)"><Remove /></el-icon>
                  <el-input v-model.number="row.receiveQty" type="number" size="small" @change="handleQtyChange(row)"></el-input>
                  <el-icon class="qty-icon" size="30" @click="increaseQty(row)"><CirclePlusFilled /></el-icon>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="基本单位数" min-width="100">
              <template #default="{ row }">
                <el-input v-model.number="row.baseUnitQty" type="number" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="批次号" min-width="150">
              <template #default="{ row }">
                <batch-selector
                  v-model="row.batchNo"
                  :data="batchList"
                  @select="handleBatchSelect($event, row)"
                  @search="handleBatchSearch"
                  @add="handleAddNewBatch"
                  @remove="handleRemoveBatch"
                />
              </template>
            </el-table-column>
            <el-table-column label="货位" min-width="120">
              <template #default="{ row }">
                <div class="location-cell" @click="handleSelectLocation(row)">
                  <el-input v-model="row.location" size="small" readonly placeholder="点击选择货位"></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商品备注" min-width="150">
              <template #default="{ row }">
                <el-input v-model="row.remark" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="自定义1-20" min-width="120">
              <template #default="{ row }">
                <el-input v-model="row.custom" size="small"></el-input>
              </template>
            </el-table-column>
			
            <el-table-column fixed="right" label="操作" width="50">
              <template #header>
                <el-icon @click="handleAddNewProduct" size="25"><CirclePlus /></el-icon>
              </template>	
              <template #default="{ row, $index }">
                <el-icon @click="removeProduct($index)" size="25"><Remove /></el-icon>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 底部统计信息 -->
        <!-- <div class="receive-summary">
          <div class="summary-item">
            <span class="label">合计数量：</span>
            <span class="value">{{ totalReceiveQty }}</span>
          </div>
          <div class="summary-item">
            <span class="label">已选商品种类：</span>
            <span class="value">{{ receiveProducts.length }}</span>
          </div>
        </div> -->
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelReceive">取消</el-button>
          <el-button type="primary" @click="confirmReceive">确认入库</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 货位选择弹窗 -->
    <location-selector
      v-model:visible="locationSelectorVisible"
      :title="'货位选择'"
      :is-batch-mode="isSelectingForBatch"
      :has-selected-items="selectedProducts.length > 0"
      @search="handleLocationSearch"
      @cancel="closeLocationSelector"
      @confirm="handleLocationConfirm"
      @apply-all="handleLocationApplyAll"
      @row-click="handleLocationRowClick"
      ref="locationSelectorRef"
    />
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  computed
} from 'vue'
import {
  CirclePlusFilled,
  Upload,
  Printer,
  WarningFilled,
  Plus,
  Remove,
  Delete,
  Search,
  LocationFilled,
  Download,
  ArrowDown
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTheme } from '@/hooks/useTheme'

// 使用主题组合API
const { themeType, themeColor } = useTheme()
console.log("颜色",themeColor.value)
// 搜索项配置列表
const searchItemsConfig = [{
    label: '外部单号',
    prop: 'externalOrderNo',
    type: 'el-input',
    placeholder: '请输入外部单号',
    defaultVisible: true
  },
  {
    label: '单据编号',
    prop: 'orderNo',
    type: 'el-input',
    placeholder: '请输入单据编号',
    defaultVisible: true
  },
  {
    label: '商品名称',
    prop: 'productName',
    type: 'el-input',
    placeholder: '请输入商品名称',
    defaultVisible: true
  },
  {
    label: '供应商',
    prop: 'supplier',
    type: 'el-input',
    placeholder: '请输入供应商',
    defaultVisible: true
  },
  {
    label: '入库类型',
    prop: 'inboundType',
    type: 'el-select',
    placeholder: '请选择入库类型',
    defaultVisible: true,
    options: [
      {
        label: '采购入库',
        value: '采购入库'
      },
      {
        label: '退货入库',
        value: '退货入库'
      },
      {
        label: '喂鸡入库',
        value: '喂鸡入库'
      },
      {
        label: '货主入库',
        value: '货主入库'
      },
      {
        label: '延期入库',
        value: '延期入库'
      }
    ]
  },
  {
    label: '货主',
    prop: 'owner',
    type: 'el-select',
    placeholder: '请选择货主',
    defaultVisible: false,
    options: [
      {
        label: 'E货主',
        value: 'E货主'
      },
      {
        label: 'D货主',
        value: 'D货主'
      }
    ]
  },
  {
    label: '时间范围',
    prop: 'timeRange',
    type: 'slot',
    slotName: 'timeRange',
    defaultVisible: false
  },
  {
    label: '下单时间',
    prop: 'orderTimeRange',
    type: 'el-date-picker-range',
    placeholder: '请选择下单时间范围',
    defaultVisible: false,
    format: 'YYYY-MM-DD',
    valueFormat: 'YYYY-MM-DD'
  }
]

// 按钮配置
const buttonsConfig = ref({
  add: { visible: true, order: 1, type: 'success', customLabel: '收货入库' },
  export: { visible: true, order: 2, type: themeType.value || 'primary' },
  delete: { visible: false },
  enable: { visible: false },
  disable: { visible: false },
  import: { visible: false },
  viewLog: { visible: false },
  edit: { visible: false }
})

// 搜索表单数据
const searchForm = reactive({
  externalOrderNo: '',
  orderNo: '',
  productName: '',
  supplier: '',
  inboundType: '',
  owner: '',
  timeRange: '近7天',
  orderTimeRange: []
})

// 表格数据相关
const tableData = ref([])
const tableLoading = ref(false)
const selectedRows = ref([])

// 分页相关
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 400
})

// 提示对话框
const tipDialogVisible = ref(false)

// 表格列配置
const tableColumns = ref([
  { prop: 'orderNo', label: '入库订单号', width: '150', minWidth: '150', visible: true },
  { prop: 'inboundType', label: '入库类型', width: '100', minWidth: '100', visible: true },
  { prop: 'owner', label: '货主', width: '100', minWidth: '100', visible: true },
  { prop: 'colorType', label: '仓库名称', width: '100', minWidth: '100', visible: true },
  { prop: 'status', label: '状态', width: '100', minWidth: '100', visible: true, slot: true },
  { prop: 'scheduledTime', label: '预约时间', width: '220', minWidth: '160', visible: true },
  { prop: 'orderTime', label: '下单时间', width: '220', minWidth: '160', visible: true },
  { prop: 'externalOrderNo', label: '外部单号', width: '150', minWidth: '150', visible: true },
  { prop: 'supplier', label: '供应商名称', width: '140', minWidth: '140', visible: true },
  { prop: 'remark', label: '单据备注', width: '150', minWidth: '150', visible: true },
  { prop: 'operation', label: '操作', width: '120', minWidth: '120', fixed: 'right', visible: true, slot: true }
])

// 收货入库弹窗相关变量
const receiveDialogVisible = ref(false)
const receiveForm = reactive({
  externalOrderNo: '',
  orderNo: '',
  inboundTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
  supplierName: '',
  productSearch: '',
  storageLocation: ''
})

// 收货入库商品表格数据
const receiveProducts = ref([])
const receiveProductsLoading = ref(false)
const selectedProducts = ref([])

// 上架货位选项
const storageLocationOptions = ref([
  { value: '选择1', label: 'A01-01-02' },
  { value: '选择2', label: 'A01-01-04' },
  { value: '选择3', label: 'A01-01-06' },
  { value: '选择4', label: 'A01-01-08' }
])

// 计算接收商品的总数量
const totalReceiveQty = computed(() => {
  return receiveProducts.value.reduce((sum, product) => {
    return sum + (product.receiveQty || 0)
  }, 0)
})

// 批次号选择相关
const batchSearchKeyword = ref('')
const currentBatchRow = ref(null)
const batchList = ref([
  {
    batchNo: 'pc24123101',
    productionDate: '2024-12-31',
    expiryDate: '2025-12-31',
    quantity: 10
  },
  {
    batchNo: 'pc24123102',
    productionDate: '2024-12-31',
    expiryDate: '2025-12-31',
    quantity: 10
  },
  {
    batchNo: 'pc24123103',
    productionDate: '2024-12-31',
    expiryDate: '2025-12-31',
    quantity: 10
  },
  {
    batchNo: 'pc24123104',
    productionDate: '2024-12-31',
    expiryDate: '2025-12-31',
    quantity: 5
  },
  {
    batchNo: 'pc24123105',
    productionDate: '2024-12-31',
    expiryDate: '2025-12-31',
    quantity: 8
  }
])

// 筛选批次号列表
const filteredBatchList = computed(() => {
  if (!batchSearchKeyword.value) {
    return batchList.value
  }
  return batchList.value.filter(item => 
    item.batchNo.toLowerCase().includes(batchSearchKeyword.value.toLowerCase())
  )
})

// 获取表格数据
const fetchTableData = async () => {
  tableLoading.value = true
  try {
    // 模拟API请求
    setTimeout(() => {
      tableData.value = [
        {
          orderNo: 'RKDD24123105',
          inboundType: '采购入库',
          owner: 'E货主',
          colorType: '华东杭州仓',
          status: '入库等待',
          scheduledTime: '2024-12-31 23:00:00',
          orderTime: '2024-12-31 21:28:10',
          externalOrderNo: 'WBDH005',
          supplier: 'E供应商',
          remark: '紧急采购入库'
        },
        {
          orderNo: 'RKDD24123104',
          inboundType: '喂鸡入库',
          owner: 'D货主',
          colorType: '华东杭州仓',
          status: '入库等待',
          scheduledTime: '2024-12-31 23:00:00',
          orderTime: '2024-12-31 20:03:27',
          externalOrderNo: 'WBDH004',
          supplier: 'D供应商',
          remark: '普通入库单'
        },
        {
          orderNo: 'RKDD24123103',
          inboundType: '货主入库',
          owner: 'E货主',
          colorType: '华东杭州仓',
          status: '集合入库',
          scheduledTime: '2024-12-31 18:00:00',
          orderTime: '2024-12-31 17:47:10',
          externalOrderNo: 'WBDH003',
          supplier: 'E供应商',
          remark: '非常紧急'
        },
        {
          orderNo: 'RKDD24123102',
          inboundType: '退货入库',
          owner: 'D货主',
          colorType: '华东杭州仓',
          status: '入库完成',
          scheduledTime: '2024-12-31 18:00:00',
          orderTime: '2024-12-31 17:46:17',
          externalOrderNo: 'WBDH002',
          supplier: 'D供应商',
          remark: '退货处理'
        },
        {
          orderNo: 'RKDD24123101',
          inboundType: '延期入库',
          owner: 'E货主',
          colorType: '华东杭州仓',
          status: '取消',
          scheduledTime: '2024-12-31 18:00:00',
          orderTime: '2024-12-31 17:45:42',
          externalOrderNo: 'WBDH001',
          supplier: 'E供应商',
          remark: '取消原因：供应商延期'
        }
      ]
      tableLoading.value = false
    }, 500)
  } catch (error) {
    console.error('获取表格数据失败', error)
    tableLoading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchTableData()
}

// 重置搜索表单
const resetSearchForm = () => {
  for (const key in searchForm) {
    if (key === 'timeRange') {
      searchForm[key] = '近7天'
    } else if (key === 'orderTimeRange') {
      searchForm[key] = []
    } else {
      searchForm[key] = ''
    }
  }
  fetchTableData()
}

// 收货入库操作
const handleReceive = () => {
  if (selectedRows.value.length > 0) {
    // 检查选中记录是否都是同一个货主
    const owners = [...new Set(selectedRows.value.map(row => row.owner))]
    if (owners.length > 1) {
      tipDialogVisible.value = true
      return
    }
    
    // 初始化收货表单数据
    const selectedRow = selectedRows.value[0]
    receiveForm.externalOrderNo = selectedRow.externalOrderNo
    receiveForm.orderNo = selectedRow.orderNo
    receiveForm.supplierName = selectedRow.supplier
    
    // 模拟获取商品数据
    fetchReceiveProducts()
    
    // 显示收货入库弹窗
    receiveDialogVisible.value = true
    
    // 确保所有商品都有snList属性
    setTimeout(() => {
      ensureSnListExists()
    }, 600) // 等待fetchReceiveProducts完成
  } else {
    ElMessage.warning('请先选择需要收货入库的记录')
  }
}

// 获取收货商品数据
const fetchReceiveProducts = () => {
  receiveProductsLoading.value = true
  
  // 模拟异步获取数据
  setTimeout(() => {
    receiveProducts.value = [
      {
        id: '1',
        productCode: '005',
        productName: 'E商品',
        barcode: '23123',
        spec: '规格1',
        unit: '件',
        length: 10,
        width: 5,
        height: 2,
        volume: 0.064,
        weight: 0.5,
        planQty: 10,
        receiveQty: 10,
        baseUnitQty: 10,
        batchNo: 'BT2024001',
        expireDate: '2025-01-01',
        snMode: 'SN',
        snList: snList.value.length > 0 ? snList.value[0].sn : '',
        location: '',
        remark: '',
        custom: ''
      },
      {
        id: '2',
        productCode: '006',
        productName: 'F商品',
        barcode: '32442',
        spec: '规格2',
        unit: '件',
        length: 10,
        width: 5,
        height: 2,
        volume: 0.064,
        weight: 0.5,
        planQty: 10,
        receiveQty: 10,
        baseUnitQty: 10,
        batchNo: 'BT2024002',
        expireDate: '2025-01-01',
        snMode: 'SN',
        snList: snList.value.length > 1 ? snList.value[1].sn : '',
        location: '',
        remark: '',
        custom: ''
      }
    ]
    
    // 确保所有商品SN是字符串类型
    receiveProducts.value.forEach((product, index) => {
      if (product.snList === undefined || product.snList === '') {
        // 尝试从snList中获取一个值
        if (snList.value.length > index) {
          product.snList = snList.value[index].sn;
        } else if (snList.value.length > 0) {
          product.snList = snList.value[0].sn;
        } else {
          product.snList = '';
        }
      } else {
        product.snList = String(product.snList);
      }
      console.log(`商品 ${product.productName} 的SN值: ${product.snList}`);
    });
    
    receiveProductsLoading.value = false
  }, 500)
}

// 增加接收数量
const increaseQty = (row) => {
  if (!row.receiveQty) {
    row.receiveQty = 0
  }
  row.receiveQty++
  row.baseUnitQty = row.receiveQty // 同步更新基本单位数
}

// 减少接收数量
const decreaseQty = (row) => {
  if (!row.receiveQty || row.receiveQty <= 0) {
    row.receiveQty = 0
    return
  }
  row.receiveQty--
  row.baseUnitQty = row.receiveQty // 同步更新基本单位数
}

// 处理数量变化
const handleQtyChange = (row) => {
  if (row.receiveQty < 0) {
    row.receiveQty = 0
  }
  row.baseUnitQty = row.receiveQty // 同步更新基本单位数
}

// 移除商品
const removeProduct = (index) => {
  receiveProducts.value.splice(index, 1)
}

// 处理商品表格选择变化
const handleProductSelectionChange = (selection) => {
  selectedProducts.value = selection
}

// 确保所有商品都有snList属性
const ensureSnListExists = () => {
  receiveProducts.value.forEach(product => {
    if (product.snList === undefined || product.snList === '') {
      // 如果snList不存在或为空，则默认设置一个SN值
      product.snList = snList.value.length > 0 ? snList.value[0].sn : '';
      console.log('初始化snList:', product.productName, product.snList);
    }
  });
  console.log('所有商品snList已初始化完成');
}

// 添加新商品
const handleAddNewProduct = () => {
  // 创建一个新商品对象
  const newProduct = {
    id: Date.now().toString(),
    productCode: `00${Math.floor(Math.random() * 900) + 100}`,
    productName: `商品${Math.floor(Math.random() * 100)}`,
    barcode: Math.floor(Math.random() * 90000) + 10000,
    spec: '规格X',
    unit: '件',
    length: 10,
    width: 5,
    height: 2,
    volume: 0.064,
    weight: 0.5,
    planQty: 10,
    receiveQty: 1,
    baseUnitQty: 1,
    batchNo: `BT2024${Math.floor(Math.random() * 900) + 100}`,
    expireDate: '2025-01-01',
    snMode: 'SN',
    snList: '', // 初始化为空字符串
    location: receiveForm.storageLocation || '', // 使用当前选择的货位
    remark: '',
    custom: ''
  }
  
  // 添加到商品列表
  receiveProducts.value.push(newProduct)
  ElMessage.success('已添加新商品')
}

// 清空商品列表
const handleClearProducts = () => {
  ElMessageBox.confirm('确定要清空所有商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    receiveProducts.value = []
    ElMessage.success('已清空商品列表')
  }).catch(() => {
    // 用户取消操作
  })
}

// 添加扫描的商品
const handleAddProduct = () => {
  if (!receiveForm.productSearch) {
    ElMessage.warning('请输入商品条码或商品编号')
    return
  }
  
  // 模拟查找商品
  const found = receiveProducts.value.find(item => 
    item.barcode === receiveForm.productSearch || 
    item.productCode === receiveForm.productSearch
  )
  
  if (found) {
    // 如果已存在，增加数量
    found.receiveQty += 1
    found.baseUnitQty = found.receiveQty // 同步更新基本单位数
    ElMessage.success('商品数量已更新')
  } else {
    // 如果不存在，添加新商品
    const newProduct = {
      id: Date.now().toString(),
      productCode: receiveForm.productSearch,
      productName: `商品${Math.floor(Math.random() * 100)}`,
      barcode: receiveForm.productSearch,
      spec: '规格X',
      unit: '件',
      length: 10,
      width: 5,
      height: 2,
      volume: 0.064,
      weight: 0.5,
      planQty: 10,
      receiveQty: 1,
      baseUnitQty: 1,
      batchNo: `BT2024${Math.floor(Math.random() * 900) + 100}`,
      expireDate: '2025-01-01',
      snMode: 'SN',
      snList: '', // 初始化为空字符串
      location: receiveForm.storageLocation || '', // 使用当前选择的货位
      remark: '',
      custom: ''
    }
    receiveProducts.value.push(newProduct)
    ElMessage.success('商品已添加')
  }
  
  // 清空搜索框
  receiveForm.productSearch = ''
}

// 取消收货
const cancelReceive = () => {
  ElMessageBox.confirm('确定要取消收货操作吗？已添加的商品信息将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    receiveDialogVisible.value = false
  }).catch(() => {
    // 用户取消操作
  })
}

// 确认收货入库
const confirmReceive = () => {
  if (receiveProducts.value.length === 0) {
    ElMessage.warning('请添加商品后再确认入库')
    return
  }
  
  if (!receiveForm.inboundTime) {
    ElMessage.warning('请选择入库时间')
    return
  }
  
  // 检查是否有商品数量为0
  const zeroQtyProducts = receiveProducts.value.filter(p => !p.receiveQty || p.receiveQty === 0)
  if (zeroQtyProducts.length > 0) {
    ElMessage.warning('存在接收数量为0的商品，请检查')
    return
  }
  
  // 提交收货入库请求
  ElMessage.success('收货入库成功')
  receiveDialogVisible.value = false
  
  // 刷新主表格数据
  fetchTableData()
}

// 导出操作
const handleExport = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要导出的记录')
    return
  }
  ElMessage.success('正在导出数据...')
}

// 打印入库单
const handlePrintOrder = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要打印的入库单')
    return
  }
  ElMessage.success('正在准备打印入库单...')
}

// 打印商品条码
const handlePrintBarcode = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要打印条码的商品')
    return
  }
  ElMessage.success('正在准备打印商品条码...')
}

// 查看详情
const handleView = (row) => {
  console.log('查看详情', row)
  ElMessage.success(`查看单号：${row.orderNo}`)
}

// 查看日志
const handleLogView = (row) => {
  console.log('查看日志', row)
  ElMessage.success(`查看单号：${row.orderNo} 的操作日志`)
}

// 处理表格选择
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchTableData()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchTableData()
}

// 处理货位推荐
const handleRecommendLocation = () => {
  if (receiveProducts.value.length === 0) {
    ElMessage.warning('没有商品可以推荐货位')
    return
  }
  
  // 模拟推荐逻辑
  receiveProducts.value.forEach(product => {
    const randomIndex = Math.floor(Math.random() * storageLocationOptions.value.length)
    product.location = storageLocationOptions.value[randomIndex].label
  })
  
  ElMessage.success('货位推荐完成')
}

// 处理导入
const handleImport = () => {
  ElMessageBox.confirm('确定导入商品数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟导入逻辑
    receiveProductsLoading.value = true
    setTimeout(() => {
      // 模拟新增两条商品数据
      const importedProducts = [
        {
          id: Date.now().toString() + '1',
          productCode: '009',
          productName: '导入商品1',
          barcode: '78945',
          spec: '规格A',
          unit: '件',
          length: 15,
          width: 8,
          height: 4,
          volume: 0.12,
          weight: 0.8,
          planQty: 5,
          receiveQty: 5,
          baseUnitQty: 5,
          batchNo: 'BT2024010',
          expireDate: '2025-06-01',
          snMode: 'SN',
          snList: '213213', // 初始化为空字符串
          location: '',
          remark: '导入商品',
          custom: ''
        },
        {
          id: Date.now().toString() + '2',
          productCode: '010',
          productName: '导入商品2',
          barcode: '45678',
          spec: '规格B',
          unit: '箱',
          length: 20,
          width: 10,
          height: 5,
          volume: 0.21,
          weight: 1.2,
          planQty: 8,
          receiveQty: 8,
          baseUnitQty: 8,
          batchNo: 'BT2024011',
          expireDate: '2025-08-01',
          snMode: '批次',
          snList: '23213213', // 初始化为空字符串
          location: '',
          remark: '导入商品',
          custom: ''
        }
      ]
      
      receiveProducts.value = [...receiveProducts.value, ...importedProducts]
      receiveProductsLoading.value = false
      ElMessage.success('商品数据导入成功')
    }, 1000)
  }).catch(() => {
    // 用户取消操作
  })
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch(status) {
    case '入库等待':
      return 'warning';
    case '入库完成':
      return 'success';
    case '集合入库':
      return 'info';
    case '取消':
      return 'danger';
    default:
      return 'primary';
  }
}

// 货位选择器相关变量
const locationSelectorVisible = ref(false)
const locationSelectorRef = ref(null)
const isSelectingForBatch = ref(false)
const currentEditingRow = ref(null)

// 处理选择货位
const handleSelectLocation = (row) => {
  currentEditingRow.value = row
  isSelectingForBatch.value = false // 设置为单行选择模式
  locationSelectorVisible.value = true
  
  // 获取货位数据
  fetchLocationData()
}

// 获取货位数据
const fetchLocationData = () => {
  // 设置加载状态
  if (locationSelectorRef.value) {
    locationSelectorRef.value.setLoading(true)
  }
  
  // 模拟异步获取数据
  setTimeout(() => {
    const locations = [
      {
        id: '1',
        locationName: 'A01-01-01',
        locationType: '拣货货位'
      },
      {
        id: '2',
        locationName: 'A01-01-02',
        locationType: '拣货货位'
      },
      {
        id: '3',
        locationName: 'A01-01-03',
        locationType: '拣货货位'
      },
      {
        id: '4',
        locationName: 'A01-01-04',
        locationType: '拣货货位'
      },
      {
        id: '5',
        locationName: 'A01-01-05',
        locationType: '拣货货位'
      }
    ]
    
    // 更新组件数据
    if (locationSelectorRef.value) {
      locationSelectorRef.value.setData(locations)
      locationSelectorRef.value.setLoading(false)
    }
  }, 300)
}

// 处理货位搜索
const handleLocationSearch = (searchParams) => {
  // 在实际应用中这里应该根据搜索条件过滤数据
  fetchLocationData()
}

// 关闭货位选择器
const closeLocationSelector = () => {
  locationSelectorVisible.value = false
}

// 处理货位行点击
const handleLocationRowClick = (row) => {
  // 立即填充数据到当前编辑的行
  if (currentEditingRow.value) {
    // 更新当前行的数据
    currentEditingRow.value.location = row.locationName
    
    // 自动关闭弹窗
    locationSelectorVisible.value = false
    
    // 显示成功提示
    ElMessage.success('已设置上架货位')
  }
}

// 处理确认货位选择
const handleLocationConfirm = (location) => {
  // 获取当前编辑的行数据
  if (currentEditingRow.value) {
    // 更新当前行的数据
    currentEditingRow.value.location = location.locationName
    
    // 显示成功提示
    ElMessage.success('已设置上架货位')
  }
}

// 处理批量应用货位
const handleLocationApplyAll = (location) => {
  if (isSelectingForBatch.value) {
    // 批量应用到选中商品
    selectedProducts.value.forEach(product => {
      product.location = location.locationName
    })
  } else {
    // 应用到所有商品
    receiveProducts.value.forEach(product => {
      product.location = location.locationName
    })
  }
  
  ElMessage.success(`已将货位 ${location.locationName} 批量应用到商品`)
}

// 处理选择批次号
const handleSelectBatch = (row) => {
  currentBatchRow.value = row
}

// 处理批次行点击
const handleBatchRowClick = (row) => {
  if (currentBatchRow.value) {
    currentBatchRow.value.batchNo = row.batchNo
    
    // 关闭批次号弹窗 (通过点击页面其他区域实现)
    document.body.click()
    
    ElMessage.success('已选择批次号')
  }
}

// 处理批次号搜索
const handleBatchSearch = (keyword) => {
  console.log('搜索批次号:', keyword)
  // 实际应用中可以调用API进行搜索
}

// 处理批次选择
const handleBatchSelect = (batchData, row) => {
  ElMessage.success('已选择批次号: ' + batchData.batchNo)
}

// 处理新增批次号
const handleAddNewBatch = () => {
  // 创建新批次对象
  const newBatch = {
    batchNo: `pc${new Date().getTime().toString().slice(-8)}`,
    productionDate: '2024-12-31',
    expiryDate: '2025-12-31',
    quantity: Math.floor(Math.random() * 20) + 1
  }
  
  // 添加到批次列表
  batchList.value.push(newBatch)
  ElMessage.success('已添加新批次号')
}

// 处理删除批次号
const handleRemoveBatch = (index, batch) => {
  ElMessageBox.confirm(`确定要删除批次号 ${batch.batchNo} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    batchList.value.splice(index, 1)
    ElMessage.success('批次号已删除')
  }).catch(() => {
    // 用户取消操作
  })
}

// SN号相关数据
const snList = ref([
  { sn: 'SN24123101' },
  { sn: 'SN24123102' },
  { sn: 'SN24123103' },
  { sn: 'SN24123104' },
  { sn: 'SN24123105' }
]);

// 处理选择SN
const handleSNSelect = (snData, row) => {
  console.log('选择SN:', snData, '行数据:', row);
  row.snList = snData.sn;
  ElMessage.success('已选择SN号: ' + snData.sn);
}

// 处理SN搜索
const handleSNSearch = (keyword) => {
  console.log('搜索SN号:', keyword);
  // 实际应用中可以调用API进行搜索
}

// 处理新增SN号
const handleAddNewSN = () => {
  // 创建新SN对象
  const newSN = {
    sn: `SN${new Date().getTime().toString().slice(-8)}`
  }
  
  console.log('添加新SN:', newSN);
  // 添加到SN列表
  snList.value.push(newSN);
  ElMessage.success('已添加新SN号');
}

// 处理删除SN号
const handleRemoveSN = (index, sn) => {
  console.log('删除SN:', index, sn);
  ElMessageBox.confirm(`确定要删除SN号 ${sn.sn} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    snList.value.splice(index, 1);
    ElMessage.success('SN号已删除');
  }).catch(() => {
    // 用户取消操作
  });
}

// 页面初始化
onMounted(() => {
  fetchTableData()
})
</script>

<style lang="scss" scoped>
.pending-operation-management-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .operation-buttons-container {
    display: flex;
    margin-bottom: 15px;
    
    .extra-buttons {
      display: flex;
      margin-left: 10px;
      
      .el-button {
        display: flex;
        align-items: center;
        
        .el-icon {
          margin-right: 4px;
        }
      }
    }
  }
  
  .warning-message {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #E6A23C;
    font-size: 14px;
  }

  // 收货入库弹窗样式
  .receive-dialog-container {
    .receive-header {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 20px;
      margin-top: 15px;
      .header-item {
        display: flex;
        align-items: center;
        margin-right: 20px;
        margin-bottom: 15px;
        min-width: 350px;
        
        .label {
          width: 100px;
          text-align: right;
          margin-right: 10px;
          white-space: nowrap;
          
          &.required::before {
            content: '*';
            color: #F56C6C;
            margin-right: 4px;
          }
        }
        
        .header-input {
          width: 240px;
        }
      }
    }
    
    .product-search-action-container {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
	  .action-container{
		  margin-bottom: 0px;
	  }	
      .product-search-area {
        display: flex;
        align-items: center;
        margin-right: 20px;
        
        .search-title {
          min-width: 100px;
          text-align: right;
          margin-right: 10px;
        }
        
        .search-input-with-action {
          display: flex;
          align-items: center;
          
          .product-search-input {
            width: 250px;
          }
          
          .add-btn {
            margin-left: 10px;
          }
        }
      }
      
      .location-select-area {
        display: flex;
        align-items: center;
        margin-right: 20px;
        
        .search-title {
          min-width: 80px;
          text-align: right;
          margin-right: 10px;
        }
        
        .location-select {
          width: 190px;
        }
      }
      
      .action-button-area {
        display: flex;
        align-items: center;
        gap: 10px;
        
        :deep(.el-button) {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-left: 0;
          
          .el-icon {
            margin-right: 5px;
          }
        }
        
        :deep(.action-buttons) {
          margin-right: 0;
        }
      }
    }
    
    .product-table-container {
      margin-bottom: 15px;
      
      .el-table {
		  
		  /* 修复操作列透视问题 */
		  :deep(.el-table__fixed-right .el-table__fixed-body-wrapper) {
		    background-color: #fff !important;
		  }
		  
		  :deep(.el-table__fixed-right .el-table__cell) {
		    background-color: #fff !important;
		  }
		  
		  :deep(.el-table-fixed-column--right) {
		    background-color: #fff !important;
		    z-index: 1 !important;
		  }
		  
		  :deep(.el-table-fixed-column--right.is-first-column) {
		    background-color: #fff !important;
		    z-index: 1 !important;
		  }
		  
		  :deep(.el-table__fixed-right .cell) {
		    background-color: #fff !important;
		  }
		  
		  :deep(.el-table__fixed-right tr:hover .el-table__cell) {
		    background-color: rgba(0, 0, 0, 0.04) !important;
		  }
		  
		  :deep(.el-table__fixed-header-wrapper) {
		    z-index: 12 !important;
		  }
        .qty-editor {
          display: flex;
          align-items: center;
          justify-content: space-between;
          
          .qty-icon {
            font-size: 18px;
            color: var(--el-color-primary);
            cursor: pointer;
            padding: 0 5px;
            
            &:hover {
              color: var(--el-color-primary-light-3);
            }
          }
          
          .el-input {
            margin: 0 5px;
            width: 70px;
          }
        }
        
        .location-cell {
          display: flex;
          align-items: center;
          position: relative;
          
          .el-input {
            width: 100%;
          }
          
          .location-icon {
            position: absolute;
            right: 5px;
            color: var(--el-color-primary);
            cursor: pointer;
          }
        }
        
        .batch-cell {
          display: flex;
          align-items: center;
          position: relative;
          cursor: pointer;
          
          .el-input {
            width: 100%;
          }
          
          .batch-icon {
            position: absolute;
            right: 5px;
            color: var(--el-color-primary);
          }
        }
      }
    }
    
    .receive-summary {
      display: flex;
      justify-content: flex-end;
      margin-top: 15px;
      
      .summary-item {
        margin-left: 20px;
        
        .label {
          font-weight: bold;
          margin-right: 5px;
        }
        
        .value {
          color: var(--el-color-primary);
          font-weight: bold;
        }
      }
    }
  }
}

:deep(.batch-popover) {
  padding: 0;
  
  .el-popover__title {
    margin: 0;
    padding: 0;
  }
}

.batch-popover-content {
  .batch-popover-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 8px;
    
    .title {
      font-weight: bold;
      font-size: 14px;
    }
    
    .search-box {
      width: 280px;
	  display: flex;
	  flex-direction: row;
	  align-items: center;
    }
  }
  
  .el-table {
    margin-bottom: 8px;
    
    :deep(tbody tr) {
      cursor: pointer;
      
      &:hover > td {
        background-color: #f5f7fa;
      }
    }
  }
}
</style> 